package com.puzzlebazar.client.main.control;

public abstract class GenericControllerImpl implements GenericController {

	protected State currentState = null;

	public GenericControllerImpl() {
		super();
	}

	@Override
	public void release() {
		leaveCurrentStateForced();
	}

	/**
	 * Leaves the current state
	 * 
	 * @return True if the user confirmed that the state has been exited, 
	 *         false if the user refused the state change.
	 */
	protected boolean leaveCurrentState() {
		if( currentState != null ) {
			if( !confirmLeaveState() ) return false;
			setConfirmStateChange(null);
			State state = currentState;
			currentState = null;
			state.exit();
		}
		return true;
	}

	/**
	 * Forces leaving the current state, never ask for user confirmation
	 */
	protected void leaveCurrentStateForced() {
		if( currentState != null ) {
			State state = currentState;
			currentState = null;
			state.exit();
		}
	}

	/**
	 * Enters a new controller state (should have left the state before)
	 * 
	 * @param newState The state to switch to
	 */
	protected void enterState(State newState) {
		assert( currentState == null );
		currentState = newState;
		currentState.enter();
	}

}